// packageE/solitaire/solitaire.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    activity_id: 0,
    activity_data: {},
    hand_goods_obj: {},
    hand_goods_id: 0,
    shareShow: false,
    specsShow: false,
    goodsPopupShow: false,
    cartListShow: false,
    currentTime: parseInt(new Date().getTime() / 1000),
    timeData: {},
    shareOptions: [
      { name: "生成海报", icon: "poster" },
      { name: "分享给好友", icon: "wechat", openType: "share" },
    ],
    goods_list: [],
    buyerListData: [],
    carList: [],
    goodsCartsTotal: {},
    language: {},
    posterShow: false,
    cartsNum: 0,
    cartsTotal: 0,
    cart_ids: [],
    good_ids: [],

    showChoose: false,
    radioChoose: "",
    dispatch_types: [],

    networkLoading: false, //网络请求

    buyerListDataLimit: [],
    page: 1, //分页数，当前页数
    isLoadMore: true, //判断是否要加载更多的标志
    total_page: 0, //总页

    end_time: "",
  },

  onChangeTime(e) {
    this.setData({
      timeData: e.detail,
    });
  },

  onCloseShare() {
    this.setData({ shareShow: false });
  },
  close_yz_cartList_popup() {
    this.setData({
      cartListShow: false,
    });
  },
  typeChange(event) {
    this.setData({
      radioChoose: Number(event.detail),
    });
  },
  close_yz_specs_popup(e) {
    console.log(e);
    if (e.detail.clicktype == 1) {
      //点击确认按钮
      this.addCartRequest({
        goods: { id: e.detail.goodsId },
        cartid: e.detail.cartid,
        total: e.detail.goodsCount,
        optionsId: e.detail.optionsId,
      });
      this.setData({
        specsShow: false,
        //	optionsId: e.detail.optionsId,
        //	goodsCount: e.detail.goodsCount
      });
    } else {
      this.setData({
        specsShow: false,
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let activity_id = options.activity_id;
    let scene = decodeURIComponent(options.scene);
    if (scene) {
      var info_arr = [];
      info_arr = scene.split("&");
      console.log(info_arr);
      for (let i = 0; i < info_arr.length; i++) {
        let chil_arr = [];
        chil_arr = info_arr[i].split("=");
        console.log(chil_arr);
        if (chil_arr[0] == "activity_id") {
          activity_id = chil_arr[1];
        }
        if(chil_arr[0] == "mid"){
          app._setMid(chil_arr[1]);
        }
      }
      console.log(info_arr);
    }

    if (options.mid) {
      app._setMid(options.mid);
    }

    if (activity_id && activity_id != 0) {
      this.setData({ activity_id });
      this.getData(activity_id);
      this.getBuyerData(activity_id);
      this.getCartList();
    } else this.tips("参数错误");
  },
  initData() {
    this.data.page = 1;
    this.data.isLoadMore = true;
    this.data.total_page = 0;
  },
  getData(activity_id) {
    this.initData();
    let urlStr = app.getNetAddresss(
      "plugin.community-relay.frontend.activity.activity-detail"
    );
    app._postNetWork({
      url: urlStr,
      data: { activity_id },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        // let date = new Date();
        this.data.end_time = (res.data.end_time - this.data.currentTime) * 1000;
        this.setData({
          goods_list: res.data.goods_list,
          networkLoading: true,
          activity_data: res.data,
        });
      },
    });
  },

  getBuyerData(activity_id) {
    let urlStr = app.getNetAddresss(
      "plugin.community-relay.frontend.activity.activity-buyer"
    );

    app._postNetWork({
      url: urlStr,
      data: { activity_id },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        console.log(res);
        this.setData({
          buyerListDataLimit: res.data.data,
          buyerListData: res.data.data,
        });
        this.data.isLoadMore = true;
        this.data.total_page = res.data.last_page;
        if (!this.data.total_page) {
          this.data.total_page = 0;
        }
      },
    });
  },
  _getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      // that.loading = true;
      return;
    } else {
      this.data.page += 1;
      let urlStr = app.getNetAddresss(
        "plugin.community-relay.frontend.activity.activity-buyer"
      );
      app._postNetWork({
        url: urlStr,
        data: {
          page: this.data.page,
          activity_id: this.options.activity_id,
        },
        success: (resdata) => {
          let res = resdata.data;
          this.data.isLoadMore = true;
          if (res.result === 1) {
            var nextPageData = res.data.data;
            let buyerListData = this.data.buyerListData.concat(nextPageData);
            this.setData({ buyerListData });
          } else {
            this.data.page = this.data.page - 1;
            this.data.isLoadMore = false;
          }
        },
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

  gotoOrder() {
    wx.navigateTo({
      url: "/packageA/member/myOrder_v2/myOrder_v2?status=0",
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  openGoodsDetail(e) {
    let item = e.currentTarget.dataset.item;
    if (item.id == this.data.hand_goods_id) {
      this.setData({
        goodsPopupShow: true,
      });
    } else {
      this.data.hand_goods_id = item.id;
      this.getGoodsDetails(item.id, "goodsDetails");
    }
  },

  //不同规格的同一商品求和
  calculateTotal(arr) {
    let temp = {};
    for (let i in arr) {
      let key = arr[i].goods_id;
      this.data.good_ids.push(key);
      this.data.cart_ids.push(arr[i].id);
      if (temp[key]) {
        // temp[key].goods_id = temp[key].goods_id;
        temp[key].total = temp[key].total + arr[i].total;
      } else {
        temp[key] = {};
        temp[key].goods_id = arr[i].goods_id;
        temp[key].total = arr[i].total;
        temp[key].id = arr[i].id;
      }
    }
    this.setData({
      goodsCartsTotal: temp,
    });
  },
  //统计购物车的总价格和总数量
  getFirstCart(data) {
    this.data.carts = data;
    let cartsNum = 0;
    let cartsTotal = 0;
    this.data.carts.forEach((item) => {
      cartsNum += item.total;
      cartsTotal += item.total * item.goods.price;
    });
    cartsTotal = parseFloat(cartsTotal).toFixed(2);
    this.setData({
      cartsNum,
      cartsTotal,
    });
    this.calculateTotal(this.data.carts);
  },

  openShareShow() {
    this.setData({
      shareShow: true,
    });
  },

  openCartListPopup() {
    this.setData({
      cartListShow: !this.data.cartListShow,
    });
  },

  onSelectShare(evt) {
    this.onCloseShare();
    if (evt.detail.index == 0) {
      this.setData({
        posterShow: true,
      });
    }
    console.log(evt.detail.index);
  },

  openSpecs(e) {
    let item = e.currentTarget.dataset.item;
    if (item.id == this.data.hand_goods_id) {
      this.setData({
        specsShow: true,
      });
    } else {
      this.data.hand_goods_id = item.id;
      this.getGoodsDetails(item.id, "specs");
    }
  },

  getGoodsDetails(id, type) {
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url: urlStr,
      data: { id: Number(id) },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        let name = "";
        if (type == "goodsDetails") {
          name = "goodsPopupShow";
        } else if (type == "specs") {
          name = "specsShow";
        }
        res.data.get_goods.end_time = this.data.end_time;
        console.log("1111111111111111", this.data.end_time);
        this.setData({
          [name]: true,
          hand_goods_obj: res.data.get_goods,
        });
      },
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  getCartList() {
    let activity_id = this.data.activity_id;
    let urlStr = app.getNetAddresss(
      "plugin.community-relay.frontend.activity.activity-cart"
    );
    app._postNetWork({
      url: urlStr,
      data: { activity_id },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        let carList = res.data;
        this.setData({
          carList,
        });
        this.getFirstCart(carList);
        //	this.calculateTotal(carList);
        console.log(carList);
      },
    });
  },
  updateCartNum(evt) {
    console.log(evt);
    let item = evt.target.dataset.item;
    let cartid = evt.target.dataset.cartid;
    let value = evt.detail.value;
    let total = value;
    if (value == "" || value == 0) {
      total = 0;
    }
    if (this.data.goodsCartsTotal[item.id].total == total) return;
    this.reduceCartRequest({
      goods: item,
      cartid,
      total,
    });
  },

  reduceCartNum(evt) {
    let item = evt.currentTarget.dataset.item;
    let cartid = evt.currentTarget.dataset.cartid;
    this.reduceCartRequest({ goods: item, cartid });
  },
  reduceCartRequest(obj) {
    let { goods, cartid, total } = obj;
    let id = goods.id;
    let num = 0;
    if (total || total === 0) {
      num = total;
    } else {
      let obj = this.data.goodsCartsTotal;
      num = Number(obj[id].total) - 1;
      this.data.goodsCartsTotal[id].total = num;
    }

    let urlStr = "";
    let json = {};
    if (num <= 0) {
      //清楚购物车
      urlStr = app.getNetAddresss("member.member-cart.destroy");
      json = {
        ids: cartid,
      };
    } else {
      urlStr = app.getNetAddresss("member.member-cart.updateNumV2");
      json = {
        id: cartid,
        num: num,
      };
    }
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        this.tips(res.msg);
        if (res.result == 1) {
          this.getCartList();
        }
      },
    });
  },
  addCartNum(evt) {
    let item = evt.currentTarget.dataset.item;
    let cartid = evt.currentTarget.dataset.cartid;
    console.log(item);
    this.addCartRequest({ goods: item, cartid });
  },

  //加入购物车
  addCartRequest(obj) {
    let { goods, cartid, total, optionsId } = obj;
    console.log("加入购物车");
    if (goods.vip_level_status && goods.vip_level_status.status == 1) {
      return this.tips(goods.vip_level_status.tips);
    }

    if (goods.stock == 0) {
      return this.tips("库存为零");
    }
    let num = 1;
    let urlStr = "";
    let jsons = {};
    if (!app._isTextEmpty(this.data.goodsCartsTotal[goods.id]) && cartid != 0) {
      if (this.data.goodsCartsTotal[goods.id].total >= goods.stock) {
        return this.tips("库存不足");
      }
      let obj = this.data.goodsCartsTotal;
      num = Number(obj[goods.id].total) + 1;
      if (total && total > 0) {
        num = total;
      }
      this.data.goodsCartsTotal[goods.id].total = num;
      urlStr = app.getNetAddresss("member.member-cart.updateNumV2");
      jsons = {
        id: cartid,
        num: num,
      };
    } else {
      urlStr = app.getNetAddresss("member.member-cart.store");
      if (total && total > 0) {
        num = total;
      }
      jsons = {
        goods_id: goods.id,
        total: num,
      };
      if (optionsId && optionsId > 0) jsons.option_id = optionsId;
    }

    app._getNetWork({
      url: urlStr,
      data: jsons,
      success: (resdata) => {
        var res = resdata.data;
        this.tips(res.msg);
        if (res.result == 1) {
          this.getCartList();
        }
      },
    });
  },

  cartListAdd(item) {
    console.log(item.detail);
    console.log(this.data.goodsCartsTotal);
    this.addCartRequest({
      goods: item.detail.goods,
      cartid: item.detail.id,
      total: item.detail.total + 1,
    });
  },

  cartListReduce(item) {
    console.log(item.detail);
    this.reduceCartRequest({
      goods: item.detail.goods,
      cartid: item.detail.id,
      total: item.detail.total - 1,
    });
  },

  cartListInputBlur(item) {
    let cartList = this.data.carList;
    for (let obj of cartList) {
      console.log(item);
      if (obj.id == item.detail.id) {
        if (obj.total == item.detail.total) return;
      }
    }
    this.reduceCartRequest({
      goods: item.detail.goods,
      cartid: item.detail.id,
      total: item.detail.total,
    });
  },

  goodsDetailCartAdd(evt) {
    this.setData({
      goodsPopupShow: false,
      specsShow: true,
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  closeChoose() {
    this.setData({
      showChoose: false,
    });
  },
  checkGoods() {
    let urlStr = app.getNetAddresss("memberCart.checkout");
    app._getNetWork({
      url: urlStr,
      data: {
        cart_ids: this.data.cart_ids.join(","),
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        if (res.data.need_choose == 1) {
          this.setData({
            dispatch_types: res.data.dispatch_types,
            showChoose: true,
          });
        } else {
          this.submitGoods();
        }
      },
    });
  },
  submitGoods() {
    if (this.data.showChoose && this.data.radioChoose === '') {
      return this.tips("请先选择配送方式");
    }
    if (this.data.showChoose) {
      // 配送方式有冲突
      this.data.cart_ids = [];
      for (
        let i = 0;
        i < this.data.dispatch_types[this.data.radioChoose].member_carts.length;
        i++
      ) {
        this.data.cart_ids.push(
          this.data.dispatch_types[this.data.radioChoose].member_carts[i].id
        );
      }
    }
    this.verifyFrom();
    // wx.navigateTo({
    // 	url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=-1' + '&cart_ids=' + JSON.stringify(this.data.cart_ids)
    // })
  },
  //下单前验证
  verifyFrom() {
    let that = this;
    let goods = [];
    goods.push(that.data.good_ids);
    let urlStr = app.getNetAddresss("from.div-from.isDisplay");
    urlStr += "&goods_ids=" + JSON.stringify(goods);
    app._getNetWork({
      showToastIn: false,
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          var _data = res.data;
          console.log("xxxx", _data);
          if (res.data.status && !res.data.member_status) {
            wx.showModal({
              title: "提示",
              content: "购买此商品,请补充您的个人信息",
              success(res) {
                if (res.confirm) {
                  //保税真实信息添加
                  // wx.navigateTo({
                  // 	url: '/packageB/member/address/myinfo/myinfo?tag=-1&cart_ids=' + JSON.stringify(that.data.cart_ids)
                  // })
                  wx.navigateTo({
                    url: "/packageB/member/address/myinfo/myinfo?tag=delta",
                  });
                } else if (res.cancel) {
                  console.log("用户点击取消");
                }
              },
            });
          } else {
            wx.navigateTo({
              url:
                "/packageD/buy/myOrder_v2/myOrder_v2?tag=-1" +
                "&cart_ids=" +
                JSON.stringify(that.data.cart_ids),
            });
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {},
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this._getMoreData();
    } else {
      console.log("没有更多数据");
    }
  },
  tips(msg) {
    wx.showToast({
      title: msg,
      icon: "none",
    });
    return false;
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var value = wx.getStorageSync('yz_uid');
    var mid = '';
    if (value) {
      mid = value;
    }
    return {
      title: this.data.activity_data.activity_name,
      path:
        "/packageE/community_solitaire/community_solitaire?activity_id=" +
        this.data.activity_id+ '&mid=' + mid,
    };
  },
});
